package edu.hrbeu.crc.controller;

import edu.hrbeu.crc.constant.ErrorConstant;
import edu.hrbeu.crc.context.BaseContext;
import edu.hrbeu.crc.pojo.dto.BillDTO;
import edu.hrbeu.crc.pojo.dto.ConsumptionDTO;
import edu.hrbeu.crc.pojo.query.BillQuery;
import edu.hrbeu.crc.pojo.result.PageResult;
import edu.hrbeu.crc.pojo.result.Result;
import edu.hrbeu.crc.pojo.vo.BillPageVO;
import edu.hrbeu.crc.pojo.vo.BillVO;
import edu.hrbeu.crc.service.BillService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/bill")
public class BillController {

    private final BillService billService;

    /**
     * 添加账单
     * @param billDTO
     * @return
     */
    @PostMapping
    public Result addBill(@RequestBody BillDTO billDTO) {
        log.info("添加账单：{}",billDTO.toString());
        billService.add(billDTO);
        return Result.success();
    }

    /**
     * 分页查询
     * @param billQuery
     * @return
     */
    @GetMapping("/list")
    public Result list(BillQuery billQuery) {
        billQuery.setUserId(BaseContext.getCurrentId());
        log.info("查询账单：{}",billQuery);

        PageResult<BillPageVO> p = billService.queryBillByPage(billQuery);
        return Result.success(p);
    }

    /**
     * 根据id查询账单
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getBill(@PathVariable Integer id) {
        log.info("根据id查询账单：{}",id);

        BillVO billVO = billService.getBill(id);
        return Result.success(billVO);
    }

    /**
     * 修改账单
     * @param billDTO
     * @return
     */
    @PutMapping
    public Result updateBill(@RequestBody BillDTO billDTO) {
        log.info("修改账单：{}",billDTO.toString());

        billService.updateBill(billDTO);
        return Result.success();
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result deleteBill(@RequestParam List<Integer> ids) {
        log.info("批量删除：{}",ids);

        billService.delete(ids);
        return Result.success();
    }

    /**
     * 导出账单
     * @param response
     */
    @GetMapping("/export")
    public void export(ConsumptionDTO consumptionDTO, HttpServletResponse response) {

        billService.getReport(consumptionDTO, response);
    }

    /**
     * 导入账单
     * @param file
     * @return
     */
    @PostMapping("/import")
    public Result importBill(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.endsWith(".xlsx")) {
            return Result.error(ErrorConstant.FILE_TYPE_STANDARDIZED);
        }

        billService.importBill(file);
        return Result.success();
    }
}
